package com.hc.pokemen.feature_pokemen.data.mapper

import com.hc.pokemen.feature_pokemen.domain.entity.Pokemon
import com.hc.pokemen.feature_pokemen.domain.entity.PokemonList
import com.hc.pokemen.feature_pokemen.data.model.PokemonListModel
import com.hc.pokemen.feature_pokemen.data.model.PokemonModel
import com.hc.pokemen.feature_pokemen.data.model.ResultModel
import com.hc.pokemen.feature_pokemen.domain.entity.PokemonListItem
import com.hc.pokemen.feature_pokemen.domain.entity.Stat
import com.hc.pokemen.feature_pokemen.domain.entity.Type
import kotlin.math.round


fun PokemonModel.toPokemon(): Pokemon {
    val imageUrl = this.sprites.front_default
    val types = types.map { Type(it.type.name) }
    val stats = stats.map { Stat(it.stat.name, it.baseStat) }
    return Pokemon(
        id,
        name,
        imageUrl,
        round(height * 100f) / 1000f,
        round(weight * 100f) / 1000f,
        types,
        stats
    )
}


fun ResultModel.toPokemonListItem(): PokemonListItem {
    val number = if (url.endsWith("/")) {
        url.dropLast(1).takeLastWhile { it.isDigit() }
    } else {
        url.takeLastWhile { it.isDigit() }
    }
    val url =
        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${number}.png"
    return PokemonListItem(name, url, number.toInt())
}


fun PokemonListModel.toPokemonList(): PokemonList {
    return PokemonList(count, results.map { it.toPokemonListItem() })
}